package com.m3958.firstgwt.server.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.google.common.base.Charsets;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.m3958.firstgwt.server.model.WebHost;
import com.m3958.firstgwt.server.service.AllSitesFMCfg;
import com.m3958.firstgwt.server.service.AppUtilService;
import com.m3958.firstgwt.server.service.FourOFourService;
import com.m3958.firstgwt.server.service.HttpClientService;
import com.m3958.firstgwt.server.service.RequestScopeObjectService;

import freemarker.template.Template;
import freemarker.template.TemplateException;


@Singleton
public class SolrSearchServlet extends HttpServlet{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	private Injector injector;
	
	@Inject
	HttpClientService httpclientService;
	
	@Inject
	AppUtilService aservice;
	
	@Inject
	AllSitesFMCfg fmcfg;
	
	@Inject
	protected com.google.inject.Provider<EntityManager> emp;
	/*
	 * 查找，bytitle，bycontent，bytag，bysection，obname
	 * 参数：searchfor
	 */
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		
		Optional<String> q = Optional.<String>fromNullable(req.getParameter("q"));
		Optional<String> siteId = Optional.<String>fromNullable(req.getParameter("siteId"));
		
		Optional<String> tpl = Optional.<String>fromNullable(req.getParameter("tpl"));
		
		
		String qclause;
		
		if(siteId.isPresent()){
			qclause = "siteId:" + siteId.get() + " AND " + q.or("*:*");
		}else{
			qclause = q.or("*:*");
		}
		
		String qurl = "http://search.m3958.com/solr-numberone/select?q=" + URLEncoder.encode(qclause, Charsets.UTF_8.name());
		
        HttpGet httpget = new HttpGet(qurl);
        
        HttpResponse response = httpclientService.getHttpClient().execute(httpget,new BasicHttpContext());
        
        HttpEntity entity = response.getEntity();
        System.out.println(response.getStatusLine());

        Map<String,Object> root = new HashMap<String, Object>();
        try {
        	String docsource = EntityUtils.toString(entity);
			root.put(
			        "doc",
			        freemarker.ext.dom.NodeModel.parse(new InputSource(new StringReader(docsource))));
			if(!tpl.isPresent()){
				root.put("docsource", docsource);
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
        
        RequestScopeObjectService rso = injector.getInstance(RequestScopeObjectService.class);
        
		res.setContentType("text/html; charset=UTF-8");   
		res.setCharacterEncoding("UTF-8");
		
		Optional<WebHost> wh = Optional.<WebHost>fromNullable(rso.getRequestWebHost());
		
		
		if(wh.isPresent()){
			Template template = fmcfg.getTemplate(rso.getRequestWebHost().getTplPath(tpl.or("default-solr-tpl.ftl")), req.getLocale());
			PrintWriter writer = res.getWriter();
			try {
				template.process(root, writer);
			} catch (TemplateException e) {
				e.printStackTrace();
			}
			writer.close();
		}else{
			injector.getInstance(FourOFourService.class).send404();
		}
	}
}
